<template>
<div>
  <div class="loader-base" v-if="showLoad"><div class="loader-wrap"></div></div>
  <header class="hd-top">
    <span class="iconfont icon-left" @click="goBack"></span>
    <h2 class="title">新增地址</h2>
    <button class="btn" @click="save">保存</button>
  </header>
  <div class="page">
    <div class="form-box displayflex">
      <div class="label">联系人</div>
      <div class="ctx flex1">
        <input type="text" class="txt-rit" placeholder="请输入" v-model="Contacts">
      </div>
    </div>
    <div class="form-box displayflex">
      <div class="label">联系电话</div>
      <div class="ctx flex1">
        <input type="text" class="txt-rit" placeholder="请输入" v-model="ContactsTel">
      </div>
    </div>
    <div class="displayflex form-box mb0 lineb">
      <x-address class="address-wrap" title="省市区" v-model="addressValue" :list="addressData" placeholder="请选择" value-text-align="right">
      </x-address>
      <div class="txt-rit" style="display:none" id="addressChinese">{{addressValue[0] | province}}/{{addressValue[1] | city}}/{{addressValue[2] | district}}</div>
      <i class="iconfont icon-right"></i>
    </div>
    <div class="form-box displayflex">
      <div class="label">详细地址</div>
      <div class="ctx flex1">
        <textarea placeholder="请输入" v-model="Address"></textarea>
      </div>
    </div>
    <div class="form-box displayflex" v-if="type == 2">
      <div class="label">消毒截止时间</div>
      <div class="ctx flex1 txt-rit">
        <datetime v-model="valueStart1" 
          format="HH:mm:ss"
          hour-row="{value}点" minute-row="{value}分">{{valueStart1}}</datetime>
      </div>
      <i class="iconfont icon-right"></i>
    </div>

  </div>
  <div @click="save" class="btn-bottom"><div class="btn">确定</div></div>
  <div id="mapcontainer" style="display:none; width:0px; height:0px"></div>
</div>
</template>

<script>
import {
  iosProvinces,
  iosCitys,
  iosCountys
} from "@/components/share/area/areaData_v2.js";
export default {
  name:'addressForm',
  data() {
    return {
      addressValue: [],
      addressData: [],
      Contacts: "",
      ContactsTel: "",
      Address: "",
      valueStart1: "请选择",
      showLoad: false,
      hasAccount: false,
      openAccount:false,
      userbiztype:'',
    };
  },
  computed: {
    userinfo() {
      if (localStorage.UserInfo) {
        return JSON.parse(localStorage.UserInfo);
      }
    },
    type(){
      return this.$route.query.type;
    },
    id(){
      return this.$route.query.AddressGuid;
    },
    mine(){
      return this.$route.query.mine;
    }
  },
  watch:{
    valueStart1(n,o){
      this.valueStart1 = n.replace(':ss','');
    },
  },
  created() {
    this.getData();
  },
  methods: {
    goBack() {
      this.$router.go(-1);
    },
    getData() {
      this.addressData = this.ChinaAddressV3Data;
      var self = this;
      var id = this.$route.query.AddressGuid;
      if (id) {
        var query = {
          Guid: id
        };
        this.showLoad = true;
        this.Ajax.post("SearchGuidCustomerAddress", query).then(function(resp) {
          self.showLoad = false;
          var cus = resp.Data;
          self.Contacts = cus.Contacts;
          self.ContactsTel = cus.ContactsTel;
          self.Address = cus.Address;
          self.addressValue.push(cus.Province);
          self.addressValue.push(cus.City);
          self.addressValue.push(cus.District);
          if(cus.SterilizeTime != null && cus.SterilizeTime != '')
          {
            self.valueStart1 = cus.SterilizeTime;
          }
          if(cus.StaffID)
          {
            self.hasAccount = true;
          }
        });
      }
      else
      {
        this.initMap();
      }
    },
    initMap(){
      this.showLoad = true;
      var map = new AMap.Map("mapcontainer", {});
      this.getCurrent(map);
    },
    getCurrent(map) {
      var _this = this;
      var geolocation = null;
      map.plugin("AMap.Geolocation", function() {
        geolocation = new AMap.Geolocation({
          enableHighAccuracy: true, //是否使用高精度定位，默认:true
          timeout: 10000, //超过10秒后停止定位，默认：无穷大
          maximumAge: 0, //定位结果缓存0毫秒，默认：0
          convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
          showButton: true, //显示定位按钮，默认：true
          buttonPosition: "LB", //定位按钮停靠位置，默认：'LB'，左下角
          buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
          showMarker: true, //定位成功后在定位到的位置显示点标记，默认：true
          showCircle: true, //定位成功后用圆圈表示定位精度范围，默认：true
          panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
          zoomToAccuracy: true //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        });
        // ios环境切换到使用远程https定位
        if (AMap.UA.ios) {
          //使用远程定位，见 remogeo.js
          var remoGeo = new RemoGeoLocation();
          //替换方法
          navigator.geolocation.getCurrentPosition = function() {
              return remoGeo.getCurrentPosition.apply(remoGeo, arguments);
          };
          //替换方法
          navigator.geolocation.watchPosition = function() {
              return remoGeo.watchPosition.apply(remoGeo, arguments);
          };
        }
        
        map.addControl(geolocation);
        geolocation.getCurrentPosition();
        AMap.event.addListener(geolocation, "complete", onComplete); //返回定位信息
        AMap.event.addListener(geolocation, "error", onError); //返回定位出错信息
      });
      /*
       *解析定位结果
       */
      function onComplete(data) {
        _this.showLoad = false;
        var str = "定位成功:";
        str += "经度：" + data.position.getLng();
        str += "纬度：" + data.position.getLat();
        str += "精度：" + data.accuracy + " 米";
        str += "是否经过偏移：" + (data.isConverted ? "是" : "否");
        console.log(data);
        var provinceTxt = _this.province(data.addressComponent.province), cityTxt = _this.city(data.addressComponent.city), districtTxt = _this.district(data.addressComponent.district);
        var fullText = provinceTxt + cityTxt + districtTxt;
        _this.addressValue.push(provinceTxt);
        _this.addressValue.push(cityTxt);
        _this.addressValue.push(districtTxt);
        _this.Address = data.formattedAddress.replace(fullText,'');
      }
      /*
       *解析定位错误信息
       */
      function onError(data) {
        alert(data.message)
        _this.showLoad = false;
        var str = "定位失败";
        str += "错误信息：";
        switch (data.info) {
          case "PERMISSION_DENIED":
            str += "浏览器阻止了定位操作";
            break;
          case "POSITION_UNAVAILBLE":
            str += "无法获得当前位置";
            break;
          case "TIMEOUT":
            str += "定位超时";
            break;
          default:
            str += "未知错误";
            break;
        }
        console.log(str);
      }
    },
    province(val) {
      var reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
      if (reg.test(val)) {
        return val;
      }
      if (val && val != null && val != "undefined") {
        for (var i = 0; i < iosProvinces.length; i++) {
          if (iosProvinces[i].id == val) {
            return iosProvinces[i].value;
          }
        }
      }
    },
    city(val) {
      var reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
      if (reg.test(val)) {
        return val;
      }
      if (val && val != null && val != "undefined") {
        for (var i = 0; i < iosCitys.length; i++) {
          if (iosCitys[i].id == val) {
            return iosCitys[i].value;
          }
        }
      }
    },
    district(val) {
      var reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
      if (reg.test(val)) {
        return val;
      }
      if (val && val != null && val != "undefined") {
        for (var i = 0; i < iosCountys.length; i++) {
          if (iosCountys[i].id == val) {
            return iosCountys[i].value;
          }
        }
      }
    },
    save() {
      var self = this;
      if (!self.Contacts) {
        self.$vux.toast.show({
          type: "warn", //success, warn, cancel, text
          text: "请输入联系人名称！"
        });
        return false;
      }
      if (!self.ContactsTel) {
        self.$vux.toast.show({
          type: "warn", //success, warn, cancel, text
          text: "请输入联系人电话！"
        });
        return false;
      }
      var testTel = /^1[345789]\d{9}$/;
      if (!self.ContactsTel || !testTel.test(self.ContactsTel)) {
          self.$vux.toast.show({
          type: "warn", //success, warn, cancel, text
          text: "请输入正确格式的手机号"
        });
        return false;
      }
      if (!self.addressValue[0]) {
        self.$vux.toast.show({
          type: "warn", //success, warn, cancel, text
          text: "请选择省份！"
        });
        return false;
      }
      if (!self.addressValue[1]) {
        self.$vux.toast.show({
          type: "warn", //success, warn, cancel, text
          text: "请选择城市！"
        });
        return false;
      }
      if (!self.addressValue[2]) {
        self.$vux.toast.show({
          type: "warn", //success, warn, cancel, text
          text: "请选择区域！"
        });
        return false;
      }
      if (!self.Address) {
        self.$vux.toast.show({
          type: "warn", //success, warn, cancel, text
          text: "请输入详情地址！"
        });
        return false;
      }
      this.doPost();
      // var content = '';
      // if(this.type == 1)
      // {
      //   self.userbiztype = 'warehouse';
      //   content = '是否同时开通仓管员账户？';
      // }
      // if(this.type == 2)
      // {
      //   self.userbiztype = 'Cargoreceiver';
      //   content = '是否同时开通收货员账户？';
      // }

      // this.$vux.confirm.show({``
      //   title:'提示',
      //   content: content,
      //   onConfirm () {
      //     alert(2)
      //     self.openAccount = true;
      //     self.doPost();
      //   },
      //   onCancel (){
      //     alert(1)
      //     self.doPost();
      //   }
      // });
    },

    doPost(){
      var self = this;
      this.showLoad = true;
      var types = this.$route.query.type;
      var id = this.$route.query.AddressGuid;
      var query = {
        CcGuid: this.userinfo.StaffID,
        Province: self.addressValue[0],
        City: self.addressValue[1],
        District: self.addressValue[2],
        Address: self.Address,
        Contacts: self.Contacts,
        ContactsTel: self.ContactsTel,
        IsChecked: "Y",
        LoginedStaffID: this.userinfo.StaffID,
        LoginedName: this.userinfo.Name,
        type: types,
      };

      if(this.valueStart1 != '请选择'){
        query.SterilizeTime = this.valueStart1;
      }

      if (id) {
        query.Guid = id;
        query.IsDeleted = "N";
      }

      // if(this.openAccount) {
      //   query.UserBizType = this.userbiztype;
      //   query.BizState = 'Y';
      //   query.TenantGuid = this.userinfo.TenantGuid;
      //   query.CorpGuid = this.userinfo.CorpGuid;
      //   query.CorpName = this.userinfo.CorpName;
      //   query.AreaFullText = document.getElementById('addressChinese').innerHTML;
      // }
      
      this.Ajax.post("OperateCustomerAddressAPI", query).then(function(resp) {
        self.showLoad = false;
        if (resp.IsSuccess) {
          self.$vux.toast.show({
            type: "success", //success, warn, cancel, text
            text: "保存成功！"
          });
          var query = self.$route.query;
          query.mine = self.$route.query.mine
          self.$router.push({
            path: "/address",
            query: query
          });
        } 
        else 
        {
          self.$vux.toast.show({    
            type: "warn", //success, warn, cancel, text
            text: resp.ErrorMessage,
          });
        }
      });
    },
  }
};
</script>